//go:build ignore

package main

import (
	"bytes"
	"fmt"
	"go/format"
	"runtime/metrics"
	"slices"
	"strings"
)

func varname(metric string) string {
	name, unit, ok := strings.Cut(metric, ":")
	if !ok {
		panic("didn't find ':' on " + metric)
	}

	name = "idx" + name + "_" + unit
	name = strings.ReplaceAll(name, "/", "_")
	name = strings.ReplaceAll(name, "-", "_")

	return name
}

type idxname struct {
	idx  string
	name string
}

// TODO: we could also get the number of buckets for histograms, and preprocess other stuff.

func main() {
	var all []idxname
	for _, m := range metrics.All() {
		if !strings.HasPrefix(m.Name, "/godebug/") {
			all = append(all, idxname{varname(m.Name), m.Name})
		}
	}
	slices.SortFunc(all, func(a, b idxname) int {
		return strings.Compare(a.idx, b.idx)
	})

	var out bytes.Buffer

	fmt.Fprintln(&out, `package plot
// Code generated by internal/plot/indices_gen.go; DO NOT EDIT.

//lint:file-ignore ST1003 Ignore underscore in generated index names
//lint:file-ignore U1000 Ignore unused indices. they're generated
`)
	fmt.Fprintln(&out, `var (`)
	for _, m := range all {
		fmt.Fprintf(&out, "%s = mustidx(%q)\n", m.idx, m.name)
	}
	fmt.Fprintln(&out, `)`)

	formatted, err := format.Source(out.Bytes())
	if err != nil {
		fmt.Println("format error:", err)
		fmt.Printf("%s", out.String())
		panic(err)
	}
	fmt.Println(string(formatted))
}
